import java.util.Arrays;

public class TestHeap {

    public int[] elem;
    public int UsedSize;
    public TestHeap(){
        this.elem=new int[10];
    }

    public void func(int[] array){
        for (int i = 0; i < elem.length; i++) {
            elem[i]=array[i];
            UsedSize++;
        }

    }
    //创造大根堆
    public void createBigHeap(){//创造大根堆
        for (int parent=(UsedSize-1-1)/2;parent>=0;parent--){
            siftDown(parent,UsedSize);
        }
    }

    public void siftDown(int parent,int end){//排序大根堆

        int child=(parent*2)+1;
        while(child<end){
            if(child+1<end && elem[child]<elem[child+1]){
                child++;
            }

            if(elem[child]>elem[parent]){
                //交换
                swap(child,parent);
                parent=child;
                child=parent*2+1;

            }else{
              break;
            }
        }
    }
    //交换
    public void swap(int i,int j){
        int tmp=elem[i];
        elem[i]=elem[j];
        elem[j]=tmp;
    }
//    删除
    public int  poll(){
        int tmp=elem[0];
        elem[0]=elem[UsedSize-1];
        UsedSize--;
        siftDown(0,UsedSize);
        return  tmp;
    }

    //插入
    public void offer(int val){
        //判断是否满
        if(isFull()){//扩容
           this.elem=Arrays.copyOf(elem,2*elem.length);
        }
        elem[UsedSize]=val;//插入最后面
        UsedSize++;
        siftUp(UsedSize-1);

    }
    public void siftUp(int child){
        int parent=(child-1)/2;
        while(child>0){
            if(elem[child]>elem[parent]){
                swap(child,parent);
                child=parent;
                parent=(child-1)/2;
            }else{
                break;
            }
        }
    }
    public boolean isFull(){
        return elem.length==UsedSize;
    }
}
